package com.sinoglobal.ningxia.frame;

import android.app.Application;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.wifi.WifiManager;
import android.support.multidex.MultiDex;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;

import com.bugtags.library.Bugtags;
import com.orhanobut.logger.LogLevel;
import com.orhanobut.logger.Logger;
import com.sinoglobal.ningxia.utils.CrashHandler;
import com.sinoglobal.ningxia.utils.EquipmentUtil;
import com.sinoglobal.ningxia.utils.LocalCache;
import com.sinoglobal.ningxia.utils.MContants;
import com.sinoglobal.ningxia.utils.SharedPreferenceUtil;
import com.sinoglobal.sinostore.SinoStore;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.cookie.CookieJarImpl;
import com.zhy.http.okhttp.cookie.store.MemoryCookieStore;
import com.zhy.http.okhttp.https.HttpsUtils;

import java.io.File;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.util.concurrent.TimeUnit;

import cn.jpush.android.api.JPushInterface;
import okhttp3.Cache;
import okhttp3.OkHttpClient;

//创建，终止，内存不足和配置改变
public class FlyApplication extends Application implements Serializable {

    private static final long serialVersionUID = 6779003566719082853L;
    public static boolean NO_NETWORK; // 异步请求是否需要网络 ：true 需要，false 不需要
    public static boolean IS_EXIST_SDCARD;
    public static String DIR; // 获取SD路径
    public static String CACHE_DIR_SD; // 资源缓存的SD卡的文件
    public static String CACHE_DIR_SYSTEM; // 资源缓存的SYSTEM;卡的文件
    public static final String WHOLESALE_CONV = ".cach";
    public static String LOG; // 日志保存的SD卡的目录
    public static String AllLOG;
    // 终端id，根据设备ime号加上md5值生成的唯一id，方便统计
    public static String TERMINAL_ID;
    public static final String DBVERSION_SYS = "DBVERSION_SYS";
    // public static String USER_ID = "11031"; // 会员Id
    public static Context context;
    public static boolean IS_CLIENTUP_DATE; // 客户端有升级，需要进行提示
    public static int NOW_VERSION; // 客户端当前版本号
    public static boolean IS_FIRST = false; // 是否第一次使用客户端，true是，false不是
    public static long THE_LAST_TIME; // 上一次使用时间，
    public static boolean IS_LOGIN; // 是否登录状态
    public static int LOADING_PROCESS = 0; // 下载进度
    public static String DOWNLOAD_CLIENT_PATH; // 储存路径
    public static boolean IS_UMENG = true; // 友盟统计控制开关，true允许使用，false则反, // //
    // 配置后需要在下次启动后生效
    public static boolean isTencent = false;// 腾讯微博是否绑定
    public static boolean isSina = false;// 新浪微博是否绑定
    public static int widthPixels;// 屏幕宽度
    public static int heightPixels;// 屏幕宽度
    public static String FROM_ONE = "1";
    public static String FROM_TWO = "2";
    public static Bitmap PhotoBitmap;//用户的头像
    public static String sUniquelyCode;// imei号

    public static boolean isShowPic = true;// 无图模式 true 显示图片 false 不显示
    public static boolean netShow = false;// 网络切换时提醒用户标志，确保只提醒一次
    public static float ScreenLight;
    // 版本号
    public static int VERSION_Code;
    public static String userId = "";// 用户UserId
    public static String jiFen = "";// 积分
    public static String userCenterId = "";// 用户中心id
    public static String myCollectionTabCateNum = "";//
    public static String myCollectionTabEntertainmentNum = "";//
    public static String myCollectionTabNewsNum = "";//
    public static String myCollectionTabColumnNum = "";//
    public static String myCollectionTabSettleNum = "";//
    public static String latitude; // 纬度
    public static String longitude; // 经度
    public static String addr;
    public static int density;// 手机密度
    public static String isFromCollection = "isFromCollection";
    public static String coortype;
    public static boolean isGpsFlag = true;
    public static boolean isGpsFlag1 = true;
    public static int isInActivityFlag = 0;// 1为娱乐
    public static int isInActivityFlag1 = 0;// 2为美食
    public static long CacheSize = 30 * 1000 * 1000;

    @Override
    public void onCreate() {
        context = this;
        // initConstants();
        initParameter();
        Logger.init("XINNUO");
        //在这里初始化BugTags
        Bugtags.start("dcae308519eb56eb66d6f1ad91dfaf8d", this, Bugtags.BTGInvocationEventNone);
        super.onCreate();
        JPushInterface.setDebugMode(true);    // 设置开启日志,发布时请关闭日志
        JPushInterface.init(this);            // 初始化 JPush
        initOkHttp();
        Logger.init("XinNuo").logLevel(LogLevel.FULL);
    }

    public void initOkHttp() {
        /**
         * Okhttp配置文件
         */
        HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(null, null, null);
        CookieJarImpl cookieJar1 = new CookieJarImpl(new MemoryCookieStore());
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(5000L, TimeUnit.MILLISECONDS)
                .readTimeout(5000L, TimeUnit.MILLISECONDS)
                .cookieJar(cookieJar1)
                .cache(new Cache(new File(LocalCache.CACHE_DIR + "/ok"), CacheSize))
                .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager)
                .build();
        OkHttpUtils.initClient(okHttpClient);
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
    }

    /**
     * @author ty
     * @createdate 2012-7-2 下午5:41:46
     * @Description: 初始化可变参数
     */
    public void initParameter() {
        if (MContants.test) {
            CrashHandler crashHandler = CrashHandler.getInstance();
            crashHandler.init(getApplicationContext());
        }

        try {
            EquipmentUtil.getInstance(context).getTerminalPID();
        } catch (Exception e) {
            e.printStackTrace();
        }

        DisplayMetrics dm = getApplicationContext().getResources().getDisplayMetrics();
        widthPixels = dm.widthPixels;
        heightPixels = dm.heightPixels;
        density = dm.densityDpi;
        userId = SharedPreferenceUtil.getString(context, "id");
        jiFen = SharedPreferenceUtil.getString(context, "jifen");
        userCenterId = SharedPreferenceUtil.getString(context, "userCenterId");
        String username = SharedPreferenceUtil.getString(context, "username");
        String nickname = SharedPreferenceUtil.getString(context, "nickname");
        // 初始化商城
        SinoStore.init(context, userId, userCenterId, username, nickname, jiFen);
    }

    public static final String getUniquely(Context context) {
        if (TextUtils.isEmpty(sUniquelyCode)) {
            TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            sUniquelyCode = tm.getDeviceId();
            if (TextUtils.isEmpty(sUniquelyCode)) {
                WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                sUniquelyCode = wm.getConnectionInfo().getMacAddress();
            }

            if (TextUtils.isEmpty(sUniquelyCode)) {
                sUniquelyCode = getUniquelyCodeFromMacAddress(getLocalMacAddress());
            }
        }
        return sUniquelyCode;
    }

    private static String getUniquelyCodeFromMacAddress(String macAddress) {
        return macAddress.replaceAll(":", "");
    }

    private static String getLocalMacAddress() {
        String macAddr = null;
        char[] buf = new char[1024];
        InputStreamReader isr = null;

        try {
            Process pp = Runtime.getRuntime().exec("busybox ifconfig eth0");
            isr = new InputStreamReader(pp.getInputStream());
            isr.read(buf);
            macAddr = new String(buf);
            int start = macAddr.indexOf("HWaddr") + 7;
            int end = start + 18;
            macAddr = macAddr.substring(start, end);
        } catch (Exception e) {
            macAddr = "Read Exception";
        }
        return macAddr;
    }
}
